package org.ma5d;

import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class InstanceTest {

    public static void main(String[] args) {
        JobDetail job = JobBuilder.newJob(InstanceJob.class)
                .withIdentity("job1", "jGroup1")
                .usingJobData("name", "ma5d")
                .usingJobData("description", "job的参数")
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "tGroup1")
                .usingJobData("year", 2024)
                .usingJobData("description", "trigger 参数")
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInMilliseconds(1).withRepeatCount(1))
                .build();

        try {
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.scheduleJob(job, trigger);
            scheduler.start();
            TimeUnit.SECONDS.sleep(10);
            scheduler.shutdown();
        } catch (SchedulerException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static class InstanceJob implements Job {

        private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        @Override
        public void execute(JobExecutionContext context) throws JobExecutionException {

            // 打印 job 和 jobDetail
            System.out.println("执行任务:" + sdf.format(new Date()) + ", job:" + System.identityHashCode(this));
            System.out.println("执行任务:" + sdf.format(new Date()) + ", jobDetail:" + System.identityHashCode(context.getJobDetail()));

            System.out.println("--------");
        }
    }
}